﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace Utils
{
    public class CookieParam
    {
        private string domain;

        public string Domain
        {
            get { return domain; }
            set { domain = value; }
        }

        private string key;

        public string Key
        {
            get { return key; }
            set { key = value; }
        }


        private string data;

        public string Data
        {
            get { return data; }
            set { data = value; }
        }
    }

    public class CookieHeler2
    {
        public static int ExpiresMinutes = 30;

        public CookieHeler2()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        public static void SetCookieValue(CookieParam cookieParam)
        {
            if (string.IsNullOrEmpty(cookieParam.Key) || string.IsNullOrEmpty(cookieParam.Data))
            {
                return;
            }

            DateTime dt = DateTime.Now;

            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(3, cookieParam.Key, dt,
                dt.AddMinutes(ExpiresMinutes), false, cookieParam.Data);

            string text = FormsAuthentication.Encrypt(newTicket);

            if ((text == null) || (text.Length < 1))
            {
                throw new HttpException("Unable_to_encrypt_cookie_ticket");
            }

            HttpCookie newUserCookie = new HttpCookie(cookieParam.Key);
            newUserCookie.Value = text;
            newUserCookie.Expires = DateTime.Now.AddMinutes(ExpiresMinutes);
            newUserCookie.Path = "/";
            newUserCookie.HttpOnly = true;
            if (!string.IsNullOrEmpty(cookieParam.Domain) && HttpContext.Current.Request.Url.Host.EndsWith(cookieParam.Domain))
            {
                newUserCookie.Domain = cookieParam.Domain;
            }
            HttpContext.Current.Response.Cookies.Add(newUserCookie);
        }

        /// <summary>
        /// 获取Cookie内的值（解密）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCookieValue(string key)
        {
            HttpCookie userCookie = HttpContext.Current.Request.Cookies[key];

            if (userCookie != null)
            {

                FormsAuthenticationTicket ticket;
                try
                {
                    ticket = FormsAuthentication.Decrypt(userCookie.Value);
                    if (ticket != null)
                    {
                        return ticket.UserData;
                    }
                }
                catch
                {
                    return string.Empty;
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 解密Cookie中的值
        /// </summary>
        /// <param name="cookieValue">要解密的值</param>
        /// <returns>解密后的值</returns>
        public static string DecryptCookie(string cookieValue)
        {

            FormsAuthenticationTicket ticket;
            try
            {
                ticket = FormsAuthentication.Decrypt(cookieValue);
                if (ticket != null)
                {
                    return ticket.UserData;
                }
            }
            catch
            {
            }
            return string.Empty;
        }

        /// <summary>
        /// 设置Cookie内的值（加密）
        /// </summary>
        /// <param name="key"></param>
        /// <param name="strData"></param>
        public static void SetCookieValue(string key, string strData)
        {
            if (string.IsNullOrEmpty(strData))
            {
                return;
            }

            DateTime dt = DateTime.Now;
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(3, key, dt,
                dt.AddMinutes(ExpiresMinutes), false, strData);

            string text = FormsAuthentication.Encrypt(newTicket);

            if ((text == null) || (text.Length < 1))
            {
                throw new HttpException("Unable_to_encrypt_cookie_ticket");
            }

            HttpCookie newUserCookie = new HttpCookie(key);
            newUserCookie.Value = text;
            newUserCookie.Expires = DateTime.Now.AddMinutes(ExpiresMinutes);
            newUserCookie.Path = "/";
            newUserCookie.HttpOnly = true;
            HttpContext.Current.Response.Cookies.Add(newUserCookie);

        }

        /// <summary>
        /// 设置Cookie内的值（加密）
        /// </summary>
        /// <param name="key"></param>
        /// <param name="strData"></param>
        /// <param name="cookie"></param>
        public static void SetCookieValue(string key, string strData, out HttpCookie cookie)
        {
            if (strData == null)
            {
                cookie = null;

                return;
            }

            DateTime dt = DateTime.Now;
            FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(3, key, dt,
                dt.AddMinutes(ExpiresMinutes), false, strData);

            string text = FormsAuthentication.Encrypt(newTicket);

            if ((text == null) || (text.Length < 1))
            {
                throw new HttpException("Unable_to_encrypt_cookie_ticket");
            }

            HttpCookie newUserCookie = new HttpCookie(key);
            newUserCookie.Value = text;
            newUserCookie.Expires = DateTime.Now.AddMinutes(ExpiresMinutes);
            newUserCookie.Path = "/";
            newUserCookie.HttpOnly = true;
            cookie = newUserCookie;

        }

        /// <summary>
        /// 获取Cookie内的值（不解密）
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetValue(string key)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(key);
            return cookie == null ? string.Empty : cookie.Value;
        }

        /// <summary>
        /// 设置Cookie内的值（不加密）
        /// </summary>
        /// <param name="key"></param>
        /// <param name="strData"></param>
        /// <returns></returns>
        public static void SetValue(string key, string strData)
        {
            HttpCookie cookie = new HttpCookie(key, strData);
            cookie.Expires = DateTime.Now.AddMinutes(ExpiresMinutes);
            cookie.HttpOnly = true;
            cookie.Path = "/";
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 清除Cookie
        /// </summary>
        /// <param name="key">Cookie的键</param>
        public static void Clear(string key)
        {
            HttpCookie cookie = new HttpCookie(key, string.Empty);
            cookie.Expires = DateTime.Now.AddMinutes(-ExpiresMinutes);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}
